package com.pzb.web.controller.wechat;

import com.alibaba.fastjson.JSONObject;
import com.pzb.common.config.WechatConfig;
import com.pzb.common.constant.Constants;
import com.pzb.common.core.controller.BaseController;
import com.pzb.common.core.domain.AjaxResult;
import com.pzb.common.utils.StringUtils;
import com.pzb.common.utils.http.HttpUtils;
import com.pzb.common.core.domain.model.WechatUser;
import com.pzb.framework.web.service.SysLoginService;
import com.pzb.wechat.domain.WechatUserAccount;
import com.pzb.wechat.service.IWechatComponentService;
import com.pzb.wechat.service.IWechatUserAccountService;
import com.pzb.wechat.service.IWechatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 系统模块Controller
 * 
 * @author Mr_Wu
 * @date 2021-11-30
 */
@RestController
@RequestMapping("/wechat")
public class SysLoginController extends BaseController
{
    private final String URL = "https://api.weixin.qq.com/sns/component/jscode2session";
    @Autowired
    private IWechatUserService wechatUserService;
    @Autowired
    private IWechatComponentService componentService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private IWechatUserAccountService wechatUserAccountService;

    /**
     * 小程序授权登录
     * @param
     * @return
     */
    @PostMapping("/loginMpWx")
    public AjaxResult loginMpWx(@RequestBody Map params)
    {
        AjaxResult ajax = AjaxResult.success("登录成功");
        Map form = (Map) params.get("form");
        String extAppid = (String) params.get("extAppid");
        Map partyData = (Map) form.get("partyData");
        String code = (String) partyData.get("code");
        //调用微信auth.code2Session接口
        String component_access_token = componentService.getApiComponentAccessToken();
        String url = URL +"?appid="+extAppid+"&js_code="+code+"&grant_type=authorization_code&component_appid="+ WechatConfig.getAppId() +"&component_access_token="+component_access_token;
        String result =  HttpUtils.sendGet(url);
        JSONObject object  = JSONObject.parseObject(result);
        String openid = object.getString("openid");
        if(StringUtils.isNotBlank(openid)){
            //查询用户是否注册
            WechatUser user = wechatUserService.selectWechatUserById(openid);
            if(user!=null){
                user.setSessionKey(object.getString("session_key"));
                wechatUserService.updateWechatUser(user);
            }else {
                //注册
                user = new WechatUser();
                user.setOpenid(openid);
                user.setExtAppid(extAppid);
                user.setSessionKey(object.getString("session_key"));
                Map userInfo = (Map) partyData.get("userInfo");
                user.setNickName((String) userInfo.get("nickName"));
                user.setGender((Integer) userInfo.get("gender"));
                user.setCountry((String) userInfo.get("country"));
                user.setProvince((String) userInfo.get("province"));
                user.setCity((String) userInfo.get("city"));
                user.setAvatarUrl((String) userInfo.get("avatarUrl"));
                wechatUserService.insertWechatUser(user);
                //查询有无资金账号
                WechatUserAccount account = wechatUserAccountService.selectWechatUserAccountByOpenId(openid,extAppid);
                //如果没有新建一个
                if (account == null) {
                    account = new WechatUserAccount();
                    account.setExtAppid(extAppid);
                    account.setOpenid(openid);
                    account.setBalance("0");
                    account.setIntegral(0);
                    wechatUserAccountService.insertWechatUserAccount(account);
                }

            }
            //系统登录
            // 生成令牌
            String token = loginService.login(user);
            JSONObject obj= new JSONObject();
            obj.put(Constants.TOKEN, token);
            obj.put("userId", openid);
            ajax.put("data",obj);

        }else {
            return AjaxResult.error("微信登录失败!");
        }
        return ajax;
    }

    @PostMapping("/test")
    public AjaxResult test()
    {
        System.err.println(getOpenid());
        System.err.println(getLoginUser());
        return AjaxResult.success();
    }



}
